package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    @Override
    public void add(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);
        addressMapper.insert(address);

    }
//地址列表吧
    @Override
    public List<Address> findList() {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, UserHolder.get().getId());
        List<Address> addressList = addressMapper.selectList(queryWrapper);

        return addressList;
    }
//修改地址回显
    @Override
    public Address findById(Long id) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getId, id);
        Address address = addressMapper.selectOne(queryWrapper);
        return address;

    }
//地址修改
    @Override
    public void update(Address address) {
        addressMapper.updateById(address);

    }
//删除地址
    @Override
    public void deleteById(List<Long> ids) {

        addressMapper.deleteBatchIds(ids);
    }
//设置默认地址
    @Override
    public void setDefault(Long id) {
        //将所有地址都设置为非默认
        Address address = new Address();
        address.setIsDefault(0);
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, UserHolder.get().getId());
        addressMapper.update(address,queryWrapper);
        //设置为默认值
        Address address1 = new Address();
        address1.setId(id);
        address1.setIsDefault(1);
        addressMapper.updateById(address1);
    }
//查询默认地址
    @Override
    public Address findDefault() {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getIsDefault, 1)
                .eq(Address::getUserId, UserHolder.get().getId());
        return    addressMapper.selectOne(queryWrapper);

    }


}
